package com.dq.controller.op.opmerchant;

import com.dq.exception.customException.AdminException;
import com.dq.controller.op.opmerchant.in.query.BroadCastQuery;
import com.dq.vo.Vo;
import com.dq.domain.sys.j2cache.Broadcast;
import com.dq.vo.baseVo.VO;
import com.dq.service.AllService;
import com.dq.utils.BeanNullUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author heshuaijun
 * @date 2019/9/1820:56
 */
@Api(description = "后台通知列表管理")
@RestController
@RequestMapping("/sys/broadCast")
public class BroadCastController extends AllService {

    @ApiOperation("所有通知列表")
    @PostMapping("/list")
    @RequiresPermissions("sys:broadCast:list")
    public Vo list(@RequestBody BroadCastQuery broadCastQuery) throws AdminException {
        broadCastQuery.format();
        Map<String, Object> query = broadCastQuery.parseMap();
        List<Broadcast> bannerList = dao.find(dao.queryAdminHql(Broadcast.class, query), query);
        PageHelper.startPage(broadCastQuery.getPage(), broadCastQuery.getSize());
        PageInfo pageInfo = new PageInfo((List<Broadcast.Vo>) VO.toVOCollection(bannerList));
        pageInfo.setTotal(dao.count(dao.countAdminHql(Broadcast.class, query), query));
        return new Vo(pageInfo);
    }

    @ApiOperation("所有通知列表")
    @PostMapping("/add")
    @RequiresPermissions("sys:broadCast:add")
    public Vo add(@RequestBody Broadcast broadcast) throws AdminException {
        broadcast.setCreateUser(shiroService.getUser());
        broadcast.setOrg(shiroService.getDept());
        return new Vo(broadCastRepository.save(broadcast).toVO(false));
    }

    @ApiOperation("所有通知列表")
    @PostMapping("/update/{id}")
    @RequiresPermissions("sys:broadCast:edit")
    public Vo update(@RequestBody Broadcast updateBroadcast, @PathVariable Long id) throws AdminException {
        Broadcast broadcast = dao.get(Broadcast.class, id);
        if (null == broadcast) {
            throw new AdminException("通知不存在");
        }
        BeanUtils.copyProperties(updateBroadcast, broadcast, BeanNullUtil.getNullPropertyNames(updateBroadcast));
        return new Vo(broadCastRepository.save(broadcast).toVO(false));
    }

    @ApiOperation("所有通知列表")
    @PostMapping("/delete/{id}")
    @RequiresPermissions("sys:broadCast:del")
    public Vo delete(@PathVariable Long id) throws AdminException {
        Broadcast broadcast = dao.get(Broadcast.class, id);
        if (null == broadcast) {
            throw new AdminException("通知不存在");
        }
        broadcast.setDeleted(true);
        broadCastRepository.save(broadcast);
        return new Vo(HttpStatus.OK);
    }
}
